package cn.itsource.ymcc.handler;

import cn.itsource.ymcc.result.JSONResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class AuthorizeFailHandler implements AuthenticationEntryPoint, AccessDeniedHandler {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        authException.printStackTrace();
        response.setContentType("application/json;charset=utf-8");
        String result = JSON.toJSONString(JSONResult.error("登录失败，没有访问权限。","401"));
        log.info(result);
        response.getWriter().print(result);
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        accessDeniedException.printStackTrace();
        response.setContentType("application/json;charset=utf-8");
        String result = JSON.toJSONString(JSONResult.error("没有访问权限","403"));
        log.info(result);

        response.getWriter().print(result);
    }
}
